#!/usr/bin/env python3.8
# -*- encoding: utf-8 -*-
'''
@File    :   main.py
@Time    :   2021/10/13 15:57:21
@Author  :   windstarry 
@Version :   1.0
'''
# here put the import lib
import os

from flask import Blueprint
from flask import render_template, flash, redirect, url_for, current_app, \
    send_from_directory, request, abort, Blueprint
from flask_login import login_required, current_user
from albumy.decorators import confirm_required, permission_required
from albumy.utils import rename_image, resize_image

from albumy.extensions import db
from albumy.models import User, Photo

main_bp = Blueprint('main',__name__)


@main_bp.route('/')
def index():
    return render_template('main/index.html')


@main_bp.route('/upload', methods=['GET', 'POST'])
@login_required   #验证登录状态
@confirm_required       #验证确认状态
@permission_required('UPLOAD')    #验证权限
def upload():
    if request.method == 'POST' and 'file' in request.files:
        #获取图片对象
        f = request.files.get('file')
        #图片重新命名
        filename = rename_image(f.filename)
        #保存图片文件
        f.save(os.path.join(current_app.config['ALBUMY_UPLOAD_PATH'], filename))
        filename_s = resize_image(f, filename, current_app.config['ALBUMY_PHOTO_SIZE']['small'])
        filename_m = resize_image(f, filename, current_app.config['ALBUMY_PHOTO_SIZE']['medium'])
        #创建图片记录
        photo = Photo(
            filename=filename,
            filename_s=filename_s,
            filename_m=filename_m,
            author=current_user._get_current_object()
        )
        db.session.add(photo)
        db.session.commit()
    return render_template('main/upload.html')


@main_bp.route('/uploads/<path:filename>')
def get_image(filename):
    return send_from_directory(current_app.config['ALBUMY_UPLOAD_PATH'], filename)


@main_bp.route('/avatars/<path:filename>')
def get_avatar(filename):
    return send_from_directory(current_app.config['AVATARS_SAVE_PATH'], filename)


@main_bp.route('/photo/<int:photo_id>')
def show_photo(photo_id):
    photo = Photo.query.get_or_404(photo_id)
    page = request.args.get('page', 1, type=int)
    per_page = current_app.config['ALBUMY_COMMENT_PER_PAGE']
    return render_template('main/photo.html', photo=photo)